<template>
	<view class="payment-page">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="back-btn" @click="navigateBack">← 返回</view>
			<view class="nav-title">确认支付</view>
			<view class="empty-space"></view>
		</view>

		<!-- 订单信息卡片 -->
		<view class="order-card">
			<view class="order-title">预约信息</view>
			<view class="order-detail">
				<view class="detail-item">
					<text class="label">预约单号：</text>
					<text class="value">{{ appointmentId || '加载中...' }}</text>
				</view>
				<view class="detail-item">
					<text class="label">就诊科室：</text>
					<text class="value">内科 - 心脏专科</text>
				</view>
				<view class="detail-item">
					<text class="label">就诊医生：</text>
					<text class="value">张医生</text>
				</view>
				<view class="detail-item">
					<text class="label">就诊时间：</text>
					<text class="value">2025-09-10 09:30</text>
				</view>
			</view>
			<view class="payment-amount">
				<text class="amount-label">支付金额：</text>
				<text class="amount-value">¥ 50.00</text>
			</view>
			<view class="time-warning">
				<text class="warning-icon">⚠️</text>
				<text class="warning-text">请在{{ formattedTime }}内完成支付，超时将取消预约</text>
			</view>
		</view>

		<!-- 支付方式选择 -->
		<view class="payment-methods">
			<view class="methods-title">选择支付方式</view>

			<!-- 余额自付 -->
			<view class="method-item" @click="selectMethod('balance')">
				<view class="method-info">
					<view class="method-icon">💰</view>
					<view class="method-detail">
						<view class="method-name">余额自付</view>
						<view class="method-desc">当前余额：¥ 320.50</view>
					</view>
				</view>
				<view class="method-select">
					<view class="select-icon" v-if="selectedMethod === 'balance'">✓</view>
				</view>
			</view>

			<!-- 支付宝支付 -->
			<view class="method-item" @click="selectMethod('alipay')">
				<view class="method-info">
					<view class="method-icon">📱</view>
					<view class="method-detail">
						<view class="method-name">支付宝支付</view>
						<view class="method-desc">使用支付宝扫码或跳转支付</view>
					</view>
				</view>
				<view class="method-select">
					<view class="select-icon" v-if="selectedMethod === 'alipay'">✓</view>
				</view>
			</view>
		</view>

		<!-- 底部支付按钮 -->
		<view class="pay-footer">
			<view class="total-amount">
				<text>实付金额：</text>
				<text class="total-value">¥ 50.00</text>
			</view>
			<view class="pay-btn" @click="confirmPayment" :disabled="!selectedMethod">
				确认支付
			</view>
		</view>
	</view>
</template>

<script>
	// 引入支付接口
	import {
		createPay
	} from '@/api/appointment.js'; // 假设接口文件路径
	export default {
		data() {
			return {
				appointmentId: null,
				selectedMethod: null, // 选中的支付方式：'balance' 或 'alipay'
				paymentTimer: null, // 倒计时计时器
				remainingTime: 600, // 剩余支付时间（秒）- 10分钟
				userId: 10086, // 实际项目中从登录信息获取
				payAmount: '50.00' // 支付金额
			};
		},
		onLoad(options) {
			this.appointmentId = options.appointmentId;
			this.startPaymentTimer();
		},
		onUnload() {
			// 页面卸载时清除计时器
			if (this.paymentTimer) {
				clearInterval(this.paymentTimer);
			}
		},
		methods: {
			// 返回上一页
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 选择支付方式
			selectMethod(method) {
				this.selectedMethod = method;
			},

			// 确认支付
			confirmPayment() {
				if (!this.selectedMethod) return;

				uni.showLoading({
					title: '处理中...'
				});

				if (this.selectedMethod === 'balance') {
					// 调用余额支付接口
					this.handleBalancePayment();
				} else {
					// 调用支付宝支付接口
					this.handleAlipayPayment();
				}
			},

			// 余额支付处理
			async handleBalancePayment() {
				try {
					const params = {
						appointmentId: this.appointmentId,
						userId: this.userId,
						amount: this.payAmount
					};

					const res = await balancePay(params);
					uni.hideLoading();

					if (res.code === 200) {
						uni.showToast({
							title: '余额支付成功',
							icon: 'success',
							duration: 2000
						});
						// 跳转支付成功页
						setTimeout(() => {
							this.navigateToSuccess();
						}, 2000);
					} else {
						uni.showToast({
							title: res.msg || '余额支付失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('余额支付失败：', error);
					uni.showToast({
						title: '支付失败，请重试',
						icon: 'none'
					});
				}
			},

			// 支付宝支付处理
			async handleAlipayPayment() {
				try {
					const params = {
						amount: this.payAmount,
						userId: this.userId,
						appointmentId: this.appointmentId
					};

					// 调用支付宝支付接口
					const res = await createPay(params);
					uni.hideLoading();
					console.log("sb", res);
					if (res.success && res.payHtml) {

						// 处理支付宝返回的HTML表单
						this.handleAlipayHtml(res.payHtml);
					} else {
						uni.showToast({
							title: res.msg || '支付宝支付请求失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('支付宝支付失败：', error);
					uni.showToast({
						title: '支付失败，请重试',
						icon: 'none'
					});
				}
			},

			// 处理支付宝HTML表单
			handleAlipayHtml(payHtml) {
				// 存储HTML到本地，跳转web-view页面
				uni.setStorageSync('alipayHtml', payHtml);
				uni.navigateTo({
					url: '/pages/alipayWebView/alipayWebView'
				});
			},

			// 跳转支付成功页
			navigateToSuccess() {
				uni.navigateTo({
					url: `/pages/paymentSuccess/paymentSuccess?appointmentId=${this.appointmentId}`
				});
			},

			// 启动支付倒计时
			startPaymentTimer() {
				this.paymentTimer = setInterval(() => {
					this.remainingTime--;
					if (this.remainingTime <= 0) {
						clearInterval(this.paymentTimer);
						// 超时处理
						uni.showModal({
							title: '支付超时',
							content: '您已超过10分钟未支付，预约已取消',
							showCancel: false,
							success() {
								uni.navigateBack({
									delta: 1
								});
							}
						});
					}
				}, 1000);
			}
		},
		computed: {
			// 格式化剩余时间为分:秒
			formattedTime() {
				const minutes = Math.floor(this.remainingTime / 60);
				const seconds = this.remainingTime % 60;
				// 补零处理，确保格式为 "00:00"
				return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			}
		}
	}
</script>

<style scoped>
	.payment-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		font-size: 14px;
	}

	/* 导航栏样式 */
	.nav-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 48px;
		background-color: #fff;
		padding: 0 16px;
		border-bottom: 1px solid #eee;
	}

	.back-btn {
		color: #333;
		font-size: 16px;
	}

	.nav-title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
	}

	.empty-space {
		width: 40px;
	}

	/* 订单信息卡片 */
	.order-card {
		background-color: #fff;
		margin: 12px;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.order-title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
		margin-bottom: 16px;
		padding-bottom: 8px;
		border-bottom: 1px solid #f5f5f5;
	}

	.detail-item {
		display: flex;
		justify-content: space-between;
		margin-bottom: 12px;
		color: #666;
	}

	.detail-item .label {
		color: #999;
	}

	.payment-amount {
		margin: 16px 0 12px;
		padding-top: 12px;
		border-top: 1px dashed #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.amount-label {
		font-size: 15px;
		color: #666;
	}

	.amount-value {
		font-size: 20px;
		font-weight: bold;
		color: #e63946;
	}

	.time-warning {
		display: flex;
		align-items: center;
		color: #e63946;
		font-size: 13px;
		padding: 8px 0;
		background-color: #fff5f5;
		border-radius: 4px;
		justify-content: center;
	}

	.warning-icon {
		margin-right: 6px;
	}

	/* 支付方式选择 */
	.payment-methods {
		background-color: #fff;
		margin: 12px;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.methods-title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
		margin-bottom: 16px;
	}

	.method-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 0;
		border-bottom: 1px solid #f5f5f5;
	}

	.method-item:last-child {
		border-bottom: none;
	}

	.method-info {
		display: flex;
		align-items: center;
	}

	.method-icon {
		font-size: 24px;
		margin-right: 12px;
	}

	.method-name {
		font-size: 15px;
		color: #333;
		margin-bottom: 4px;
	}

	.method-desc {
		font-size: 12px;
		color: #999;
	}

	.method-select {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		border: 1px solid #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.select-icon {
		color: #1677ff;
		font-weight: bold;
	}

	/* 底部支付按钮 */
	.pay-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 16px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
	}

	.total-amount {
		font-size: 15px;
	}

	.total-value {
		font-size: 18px;
		font-weight: bold;
		color: #e63946;
	}

	.pay-btn {
		background-color: #1677ff;
		color: #fff;
		border: none;
		border-radius: 20px;
		padding: 8px 24px;
		font-size: 16px;
		font-weight: 500;
		opacity: 1;
	}

	.pay-btn:disabled {
		background-color: #ccc;
		opacity: 0.7;
	}
</style>